package com.tintintech.sendmail;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * Config.loadFile($filename).getItem(); 
 * @author frk
 */
public class Config {

    public static final String CONFIG_NAME = "cfg.path";
    public static final String LOG_NAME = "log4j.configuration";
    public static AtomicBoolean SEND_MAIL_THREAD_STATUS = new AtomicBoolean(true);
    public static byte IS_START_SEND = 0;
    
    public static AtomicInteger SEND_SUCCESS_NUM = new AtomicInteger(0);
    public static AtomicInteger SEND_FAILED_NUM = new AtomicInteger(0);
    public static AtomicInteger RECV_MAIL_TOTAL = new AtomicInteger(0);
    public static final Map<String, String> GLOBALS = new HashMap<String, String>();
    
    private static final Config _instance = new Config();
    private static File f = null;
    private static Document doc = null;
    private static Element root = null;

    
    public static Config loadFile(String filename)
    {
        if (f == null)
        {
            f = new File(filename);
        }
        parseXml();
        return _instance;
    }
    
    public static final Config getInstance()
    {
        return _instance;
    }
    
    private static void parseXml()
    {
        SAXReader reader = new SAXReader();
        try {
            doc  = reader.read(f);
            root = doc.getRootElement();
        } catch (DocumentException e)
        {
            e.printStackTrace();
        }
    }
    
    @SuppressWarnings("unchecked")
    public Map<String, String> getItems(String nodeName)
    {
        Element elem = root.element(nodeName);
        List<Element> elems = elem.elements();
        int size = elems.size(), i = 0;
        Element e = null;
        Map<String, String> item = new HashMap<String, String>();
        for (; i < size; i++)
        {
            e = (Element)elems.get(i);
            item.put(e.getName(), e.getText().trim());
        }
        
        return item;
    }
    
    public void buildGlobals()
    {
        Config.GLOBALS.putAll(this.getItems("baseConfig"));
        Config.GLOBALS.putAll(this.getItems("mailConfig"));
    }
}
